<template>
    <div class="customer-list">
      <span style="font-size: 30px;position: relative; top: -10px ;">采购订单</span>
      <!-- 这里放置表格等内容 -->
        <div class="add-button-bottom-right">
          <el-button type="primary" icon="el-icon-loading" class="audit-button" @click="handleAudit">审核</el-button>
          <el-button class="delete-button" type="danger" icon="el-icon-delete" @click="handleDeleteSelected">删除</el-button>
          <el-button icon="el-icon-check" class="add-button" @click="showAddModal">新增采购订单</el-button>
        </div>
        <div style="display: flex; align-items: center;">
            <!-- 搜索框 -->
            <el-input style="width: 300px; margin: 10px 20px 10px 0;"  placeholder="请输入" prefix-icon="el-icon-search" v-model="OrderWord" @change="PurFenYe" clearable></el-input>
            <el-button icon="el-icon-search" circle  @change="PurFenYe"></el-button>&nbsp;
            <!-- 日期选择器 -->
            <el-date-picker  type="date" placeholder="选择日期" v-model="SelectedDate" @change="PurFenYe"></el-date-picker>
        </div>
          <!-- <el-divider></el-divider>-->
          <el-table :data="order"  border style="width: 100%" class="centered-table" @selection-change="handleSelectionChange"> 
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="ord_number" label="订单编号" width="140px"></el-table-column>
          <el-table-column prop="ord_supplier" label="供货商"></el-table-column>
          <el-table-column prop="ord_attribute" label="商品属性"></el-table-column>
          <el-table-column prop="ord_types" label="商品种类">
            <template slot-scope="scope"> 
              {{ scope.row.ord_types }} 种
            </template>
          </el-table-column>
          <el-table-column prop="ord_amount_due" label="应付金额">
            <template slot-scope="scope">
              ￥{{ scope.row.ord_amount_due }}
            </template>
          </el-table-column>
          <el-table-column prop="ord_to_pay" label="订单预付">
            <template slot-scope="scope">
              ￥{{ scope.row.ord_to_pay }}
            </template>
          </el-table-column>
          <el-table-column prop="ord_state" label="订单状态" width="auto">
            <template slot-scope="scope">
              <span
                :style="{
                    color: scope.row.ord_state == 1   ? '#2ab600' : 'red',
                }"
              >{{ scope.row.ord_state == 1 ? '已完成' : '未完成' }}</span>
            </template>      
          </el-table-column>

          <el-table-column prop="ord_warehouse" label="入库状态">
            <template slot-scope="scope">
              <span
              :style="{
                color:
                  scope.row.ord_warehouse == 0
                    ? 'red'
                    : scope.row.ord_warehouse == 1
                    ? 'orange'
                    : '#2ab600',
              }"
            >
              {{
                scope.row.ord_warehouse == 0
                  ? "未入库"
                  : scope.row.ord_warehouse == 1
                  ? "待入库"
                  : "已入库"
              }}
            </span>
            </template>
          </el-table-column>
          <el-table-column prop="AuditStatus" label="审核状态" width="auto">
          <template slot-scope="scope">
            <span
              :style="{
                color: scope.row.auditStatus == true ? '#2ab600' : 'red',
              }"
            >
              {{ scope.row.auditStatus == true ? "已审核" : "未审核" }}
            </span>
          </template>
        </el-table-column>

          <el-table-column prop="ord_purchase_date" label="采购日期">
            <template slot-scope="scope">
              <span>{{ formatDate(scope.row.ord_purchase_date) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200px">
            <template slot-scope="scope">
              <el-button size="mini" type="primary" icon="el-icon-edit" @click="editCustomers(scope.row)">查看</el-button>
              <!-- <el-button size="mini" type="danger" icon="el-icon-arrow-left" @click="SalesCustomers(scope.row)">退货</el-button> -->
               <el-button
              size="mini"
              :type="
                scope.row.so_Return_status == 1 ||
                scope.row.so_Return_status == 2
                  ? 'danger'
                  : 'primary'
              "
              :icon="scope.row.so_Return_status == 0 ? 'el-icon-back' : ''"
              :disabled="
                scope.row.so_Return_status == 1 ||
                scope.row.so_Return_status == 2
              "
              @click="SalesCustomers(scope.row)"
            >
              {{
                scope.row.so_Return_status == 0
                  ? "退货"
                  : scope.row.so_Return_status == 1
                  ? "待退货审核"
                  : "已退货"
              }}
            </el-button>
            </template>
          </el-table-column>
        </el-table>
        
      <el-divider></el-divider> <!-- 下划线分隔 -->
      <!-- 分页 -->
      <div>
        <el-pagination class="pagination"
          @size-change="Change"
          @current-change="YmChange"
          :current-page="currentPage"
          :page-sizes="[5, 10, 20, 50]" 
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper" 
          :total="rows">
        </el-pagination>
        
        
        <!-- 主-添加模态框 -->
        <el-dialog :visible.sync="isAddModalVisible" class="addmodel" width="70%" :before-close="PurHandleClose">
            <div class="custom-div1">
                <el-button @click="PurOrderAdd">提交新增</el-button>
            </div>
            <div class="custom-div">
                <span>新增采购订单</span>
            </div>
            <el-button class="orange-button" style="position: absolute; top: 43px; left: 10; padding: 10px;"
                @click="returnToList">返回列表</el-button>
            <el-form :model="PurAdd" class="custom-form" label-position="top">
                <div class="form-items-container">
                    <div style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 10px;">
                        <div style="display: flex; align-items: center;">
                            <label style="width: 80px; margin-right: 10px;">供货商:</label>
                            <el-select v-model="PurAdd.ord_supplier" auto-complete="off" placeholder="请选择" style="flex: 1; size:large" @change="onCustomerContactChange($event)">
                                <el-option 
                                  v-for="item in ListGou" 
                                  :key="item.vendor_head" style="width: 100%;"
                                  :label="item.ord_supplier" 
                                  :value="item.vendor_head" class="kuang">
                                </el-option>
                            </el-select>
                        </div>

                        <div style="display: flex; align-items: center;">
                            <label style="width: 80px; margin-right: 10px;">公司名称:</label>
                            <el-input v-model="PurAdd.ord_supplier_company" auto-complete="off" style="flex: 1;" class="kuang" placeholder="请输入公司名称" readonly>
                            </el-input>
                        </div>

                        <div style="display: flex; align-items: center;">
                            <label style="width: 80px; margin-right: 10px;">联系电话:</label>
                            <el-input v-model="PurAdd.ord_phone" auto-complete="off" style="flex: 1;" placeholder="请输入联系人手机" class="kuang" readonly ></el-input>
                        </div>

                        <div style="display: flex; align-items: center;">
                            <label style="width: 80px; margin-right: 10px;">供货商地址:</label>
                            <el-input v-model="PurAdd.ord_supplier_address" auto-complete="off" placeholder="请输入供货商地址" style="flex: 1;">
                            </el-input>
                        </div>

                        <div style="display: flex; align-items: center;" >
                            <label style="width: 80px; margin-right: 10px;">采购订单编号:</label>
                            <el-input v-model="PurAdd.ord_number" auto-complete="off" style="flex: 1;" class="kuang" disabled></el-input>
                        </div>

                        <div style="display: flex; align-items: center;">
                            <label style="width: 80px; margin-right: 10px;">采购属性</label>
                            <el-select v-model="PurAdd.ord_attribute" auto-complete="off" placeholder="请选择" style="flex: 1; size:large" >
                              <el-option label="配料" value="配料"></el-option>
                              <el-option label="包装" value="包装"></el-option>
                              <el-option label="其他" value="其他"></el-option>
                                <!-- <el-option 
                                  v-for="item in ListAtt" 
                                  :key="item.vendor_head" style="width: 100%;"
                                  :label="item.ord_attribute" 
                                  :value="item.vendor_head" class="kuang">
                                </el-option> -->
                            </el-select>
                        </div>

                         <div style="display: flex; align-items: center;">
                            <label style="width: 80px; margin-right: 10px;">采购日期:</label>
                            <el-date-picker v-model="PurAdd.ord_purchase_date" auto-complete="off" style="flex: 1;" class="kuang" ></el-date-picker>
                        </div>

                        <div style="display: flex; align-items: center;">
                            <label style="width: 80px; margin-right: 10px;">购货金额:</label>
                            <el-input v-model="PurAdd.ord_purchase_amount" auto-complete="off" style="flex: 1;" class="kuang" ></el-input>
                        </div>

                        <div style="display: flex; align-items: center;">
                            <label style="width: 80px; margin-right: 10px;">优惠金额:</label>
                            <el-input v-model="PurAdd.ord_discount_amount" auto-complete="off" style="flex: 1;" class="kuang" @input="updateAmountDue"></el-input>
                        </div>

                        <div style="display: flex; align-items: center;">
                            <label style="width: 80px; margin-right: 10px;">订单运费:</label>
                            <el-input v-model="PurAdd.ord_freight" auto-complete="off" style="flex: 1;" class="kuang" @input="updateAmountDue"></el-input>
                        </div>

                        <div style="display: flex; align-items: center;">
                            <label style="width: 80px; margin-right: 10px;">应付金额:</label>
                            <el-input v-model="PurAdd.ord_amount_due" auto-complete="off" style="flex: 1;" class="kuang" readonly></el-input>
                        </div>

                        <div style="display: flex; align-items: center;">
                            <label style="width: 80px; margin-right: 10px;">订单已付款:</label>
                            <el-input v-model="PurAdd.ord_to_pay" auto-complete="off" style="flex: 1;" class="kuang"></el-input>
                        </div>
                    </div>
                </div>

                <div class="button-container">
                    <el-button @click="PurFromAdd" class="custom-button">添加</el-button>
                </div>
                <!-- 采购商品列表 -->
                <div class="product-list-container">
                    <el-table :data="FromDataAdd" style="width: 100%" border >
                        <el-table-column label="序号" prop="fro_id" type="index" width="80"></el-table-column>
                        <el-table-column label="商品属性" prop="fro_purtotale"></el-table-column>
                        <el-table-column label="采购商品名称" prop="fro_purname"></el-table-column>
                        <el-table-column label="单位" prop="orders_unit" width="80"></el-table-column>
                        <el-table-column label="采购单价" prop="fro_purprice"></el-table-column>
                        <el-table-column label="采购数量" prop="fro_puramount"></el-table-column>
                        <el-table-column label="小计" prop="fro_pursubtotal"></el-table-column>
                        <el-table-column label="操作"  width="200">
                            <template>
                            <!-- <template slot-scope="scope" > -->
                                <!-- <el-button class="caoz" size="mini" type="primary" icon="el-icon-edit"
                                    @click="PurEditFrom(scope.row)">修改</el-button> -->
                                <el-button class="caoz" size="mini" type="danger" icon="el-icon-delete"
                                    @click="deleteCustomer(index)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
              <div class="pagination-wrapper">
                <el-pagination
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                  :current-page="currentPage1"
                  :page-sizes="[3,6,9,12]"
                  :page-size="pageSize1"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="totalItems">
                </el-pagination>
              </div>
            </el-form>

        </el-dialog>
        <!-- 从-采购商品添加 -->
        <el-dialog title="添加" :visible.sync="isAddProductVisible" width="350px" id="qw">
            <el-form label-width="285px">
                <el-form-item label="产品属性" style="position: relative; margin-left:-180px; top: 10px;">
                    <el-select v-model="FromAdd.fro_purtotale" placeholder="请选择" style="width: 180px;" @change="nation">
                        <el-option 
                          v-for="item in uniqueList" 
                          :key="item.di_type" 
                          :label="item.fro_purtotale"
                          :value="item.di_type">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="产品名称" style="position: relative; margin-left:-180px; top: 10px;">
                    <el-select v-model="FromAdd.fro_purname" placeholder="请选择" style="width: 180px;">
                        <el-option 
                          v-for="item in list3" 
                          :key="item.di_name" 
                          :label="item.fro_purname"
                          :value="item.di_name">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="单位" style="position: relative; margin-left:-180px; top: 10px;">
                    <el-select v-model="FromAdd.orders_unit" placeholder="请选择" style="width: 180px;">
                        <el-option 
                          v-for="item in units" 
                          :key="item.dd_label" 
                          :label="item.orders_unit"
                          :value="item.dd_label">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="单价" style="position: relative;  margin-left:-180px; top: 10px;">
                    <el-input-number v-model="FromAdd.fro_purprice" :precision="4" :min="1" :step="0.1" controls-position="right"
                        @change="updateSubtotal"></el-input-number>
                </el-form-item>
                <el-form-item label="数量" style="position: relative;  margin-left:-180px; top: 10px;">
                    <el-input-number v-model="FromAdd.fro_puramount" :min="1" :step="1" controls-position="right"
                        @change="updateSubtotal"></el-input-number>
                </el-form-item>
                <el-form-item label="小计" style="position: relative;  margin-left:-180px; top: 10px;">
                    <el-input-number v-model="FromAdd.fro_pursubtotal" :precision="4" controls-position="right"
                        disabled></el-input-number>
                </el-form-item>
            </el-form>
            <div>
                <span slot="footer" style="display: flex; justify-content: center;">
                    <el-button @click="isAddProductVisible = false"
                        style="margin-left:40px; background-color: #4FC1B0; border-color: #4FC1B0; color: #fff;">取消</el-button>
                    <el-button type="primary" @click="SubmitModelForm"
                        style="margin-left: 20px; background-color: #4FC1B0; border-color: #4FC1B0; color: #fff;">确定</el-button>
                </span>
            </div>
            
        </el-dialog>
        <!-- 主-修改模态框 -->
        <el-dialog :visible.sync="isUpdateModalVisible" class="addmodel" width="70%">
            <div class="custom-div1">
                <el-button @click="PurOrderUpdate">修改</el-button>
            </div>
            <div class="custom-div">
                <span>采购订单详情</span>
            </div>
            <el-button class="orange-button" style="position: absolute; top: 43px; left: 10; padding: 10px;"
                @click="returnToList">返回列表</el-button>
            <el-form :model="EditPurUpdate" class="custom-form" label-position="top">
                <div class="form-items-container">
                    <div style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 10px;">
                        <div style="display: flex; align-items: center;">
                            <label style="width: 80px; margin-right: 10px;">供货商:</label>
                            <el-select v-model="EditPurUpdate.ord_supplier" auto-complete="off" placeholder="请选择" style="flex: 1; size:large" @change="onCustomerContactChange($event)">
                                <el-option 
                                  v-for="item in ListGou" 
                                  :key="item.vendor_head" style="width: 100%;"
                                  :label="item.ord_supplier" 
                                  :value="item.vendor_head" class="kuang">
                                </el-option>
                            </el-select>
                        </div>

                        <div style="display: flex; align-items: center;">
                            <label style="width: 80px; margin-right: 10px;">公司名称:</label>
                            <el-input v-model="EditPurUpdate.ord_supplier_company" auto-complete="off" style="flex: 1;" class="kuang" placeholder="请输入公司名称" readonly>
                            </el-input>
                        </div>

                        <div style="display: flex; align-items: center;">
                            <label style="width: 80px; margin-right: 10px;">联系电话:</label>
                            <el-input v-model="EditPurUpdate.ord_phone" auto-complete="off" style="flex: 1;" placeholder="请输入联系人手机" class="kuang" readonly ></el-input>
                        </div>

                        <div style="display: flex; align-items: center;">
                            <label style="width: 80px; margin-right: 10px;">供货商地址:</label>
                            <el-input v-model="EditPurUpdate.ord_supplier_address" auto-complete="off" placeholder="请输入供货商地址" style="flex: 1;">
                            </el-input>
                        </div>

                        <div style="display: flex; align-items: center;" >
                            <label style="width: 80px; margin-right: 10px;">采购订单编号:</label>
                            <el-input v-model="EditPurUpdate.ord_number" auto-complete="off" style="flex: 1;" class="kuang" disabled></el-input>
                        </div>

                        <div style="display: flex; align-items: center;">
                            <label style="width: 80px; margin-right: 10px;">采购属性</label>
                            <el-select v-model="EditPurUpdate.ord_attribute" auto-complete="off" placeholder="请选择" style="flex: 1; size:large" >
                              <el-option label="配料" value="配料"></el-option>
                              <el-option label="包装" value="包装"></el-option>
                              <el-option label="其他" value="其他"></el-option>
                            </el-select>
                        </div>

                         <div style="display: flex; align-items: center;">
                            <label style="width: 80px; margin-right: 10px;">采购日期:</label>
                            <el-date-picker v-model="EditPurUpdate.ord_purchase_date" auto-complete="off" style="flex: 1;" class="kuang" ></el-date-picker>
                        </div>

                        <div style="display: flex; align-items: center;">
                            <label style="width: 80px; margin-right: 10px;">购货金额:</label>
                            <el-input v-model="EditPurUpdate.ord_purchase_amount" auto-complete="off" style="flex: 1;" class="kuang" ></el-input>
                        </div>

                        <div style="display: flex; align-items: center;">
                            <label style="width: 80px; margin-right: 10px;">优惠金额:</label>
                            <el-input v-model="EditPurUpdate.ord_discount_amount" auto-complete="off" style="flex: 1;" class="kuang" @input="updateAmountDue"></el-input>
                        </div>

                        <div style="display: flex; align-items: center;">
                            <label style="width: 80px; margin-right: 10px;">订单运费:</label>
                            <el-input v-model="EditPurUpdate.ord_freight" auto-complete="off" style="flex: 1;" class="kuang" @input="updateAmountDue"></el-input>
                        </div>

                        <div style="display: flex; align-items: center;">
                            <label style="width: 80px; margin-right: 10px;">应付金额:</label>
                            <el-input v-model="EditPurUpdate.ord_amount_due" auto-complete="off" style="flex: 1;" class="kuang" readonly></el-input>
                        </div>

                        <div style="display: flex; align-items: center;">
                            <label style="width: 80px; margin-right: 10px;">订单已付款:</label>
                            <el-input v-model="EditPurUpdate.ord_to_pay" auto-complete="off" style="flex: 1;" class="kuang"></el-input>
                        </div>
                    </div>
                </div>

                <div class="button-container">
                    <el-button @click="PurFromUpdate" class="custom-button">添加</el-button>
                </div>
                <!-- 采购商品列表 -->
                <div class="product-list-container">
                    <el-table :data="fromEditUpdate" style="width: 100%" border >
                        <el-table-column label="序号" prop="fro_id" type="index" width="80"></el-table-column>
                        <el-table-column label="商品属性" prop="fro_purtotale"></el-table-column>
                        <el-table-column label="采购商品名称" prop="fro_purname"></el-table-column>
                        <el-table-column label="单位" prop="orders_unit" width="80"></el-table-column>
                        <el-table-column label="采购单价" prop="fro_purprice"></el-table-column>
                        <el-table-column label="采购数量" prop="fro_puramount"></el-table-column>
                        <el-table-column label="小计" prop="fro_pursubtotal"></el-table-column>
                        <el-table-column label="操作"  width="200">
                            <template slot-scope="scope" >
                                <el-button class="caoz" size="mini" type="primary" icon="el-icon-edit"
                                    @click="UpdatePurEditFrom(scope.row)">修改</el-button>
                                <el-button class="caoz" size="mini" type="danger" icon="el-icon-delete"
                                    @click="UpdatedeleteCustomer(scope.row.fro_id)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
              <div class="pagination-wrapper">
                <el-pagination
                  @size-change="UdateSizeChange"
                  @current-change="UpdateCurrentChange"
                  :current-page="currentPage2"
                  :page-sizes="[3,6,9,12]"
                  :page-size="pageSize2"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="UpdateItems">
                </el-pagination>
              </div>
            </el-form>

        </el-dialog>
        <!-- 从-采购商品添加 -->
        <el-dialog title="添加" :visible.sync="isUpdateProductVisible" width="400px" id="qw">
            <el-form label-width="300px">
                <el-form-item label="产品属性" style="position: relative; margin-left:-180px; top: 10px;">
                    <el-select v-model="EditFromAdd.fro_purtotale" placeholder="请选择" style="width: 180px;" @change="FromnationAdd">
                        <el-option 
                          v-for="item in uniqueList" 
                          :key="item.di_type" 
                          :label="item.fro_purtotale"
                          :value="item.di_type">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="产品名称" style="position: relative; margin-left:-180px; top: 10px;">
                    <el-select v-model="EditFromAdd.fro_purname" placeholder="请选择" style="width: 180px;">
                        <el-option 
                          v-for="item in list3" 
                          :key="item.di_name" 
                          :label="item.fro_purname"
                          :value="item.di_name">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="单位" style="position: relative; margin-left:-180px; top: 10px;">
                    <el-select v-model="EditFromAdd.orders_unit" placeholder="请选择" style="width: 180px;">
                        <el-option 
                          v-for="item in units" 
                          :key="item.dd_label" 
                          :label="item.orders_unit"
                          :value="item.dd_label">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="单价" style="position: relative;  margin-left:-180px; top: 10px;">
                    <el-input-number v-model="EditFromAdd.fro_purprice" :precision="4" :min="1" :step="0.1" controls-position="right"
                        @change="updateSubtotal"></el-input-number>
                </el-form-item>
                <el-form-item label="数量" style="position: relative;  margin-left:-180px; top: 10px;">
                    <el-input-number v-model="EditFromAdd.fro_puramount" :min="1" :step="1" controls-position="right"
                        @change="updateSubtotal"></el-input-number>
                </el-form-item>
                <el-form-item label="小计" style="position: relative;  margin-left:-180px; top: 10px;">
                    <el-input-number v-model="EditFromAdd.fro_pursubtotal" :precision="4" controls-position="right"
                        disabled></el-input-number>
                </el-form-item>
            </el-form>
            <div>
                <span slot="footer" style="display: flex; justify-content: center;">
                    <el-button @click="isUpdateProductVisible = false"
                        style="margin-left:40px; background-color: #4FC1B0; border-color: #4FC1B0; color: #fff;">取消</el-button>
                    <el-button type="primary" @click="FromUpdateSubmit"
                        style="margin-left: 20px; background-color: #4FC1B0; border-color: #4FC1B0; color: #fff;">确定</el-button>
                </span>
            </div>
        </el-dialog>
         <!-- 从-采购商品修改 -->
        <el-dialog title="添加" :visible.sync="isUpdateProduct" width="400px" id="qw">
            <el-form label-width="300px">
                <el-form-item label="产品属性" style="position: relative; margin-left:-180px; top: 10px;">
                    <el-select v-model="EditFromUpdate.fro_purtotale" placeholder="请选择" style="width: 180px;" @change="FromnationUpdate">
                        <el-option 
                          v-for="item in uniqueList" 
                          :key="item.di_type" 
                          :label="item.fro_purtotale"
                          :value="item.di_type">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="产品名称" style="position: relative; margin-left:-180px; top: 10px;">
                    <el-select v-model="EditFromUpdate.fro_purname" placeholder="请选择" style="width: 180px;">
                        <el-option 
                          v-for="item in list3" 
                          :key="item.di_name" 
                          :label="item.fro_purname"
                          :value="item.di_name">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="单位" style="position: relative; margin-left:-180px; top: 10px;">
                    <el-select v-model="EditFromUpdate.orders_unit" placeholder="请选择" style="width: 180px;">
                        <el-option 
                          v-for="item in units" 
                          :key="item.dd_label" 
                          :label="item.orders_unit"
                          :value="item.dd_label">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="单价" style="position: relative;  margin-left:-180px; top: 10px;">
                    <el-input-number v-model="EditFromUpdate.fro_purprice" :precision="4" :min="1" :step="0.1" controls-position="right"
                        @change="updateSubtotal"></el-input-number>
                </el-form-item>
                <el-form-item label="数量" style="position: relative;  margin-left:-180px; top: 10px;">
                    <el-input-number v-model="EditFromUpdate.fro_puramount" :min="1" :step="1" controls-position="right"
                        @change="updateSubtotal"></el-input-number>
                </el-form-item>
                <el-form-item label="小计" style="position: relative;  margin-left:-180px; top: 10px;">
                    <el-input-number v-model="EditFromUpdate.fro_pursubtotal" :precision="4" controls-position="right"
                        disabled></el-input-number>
                </el-form-item>
            </el-form>
            <div>
                <span slot="footer" style="display: flex; justify-content: center;">
                    <el-button @click="isUpdateProduct = false"
                        style="margin-left:40px; background-color: #4FC1B0; border-color: #4FC1B0; color: #fff;">取消</el-button>
                    <el-button type="primary" @click="FromUpdatePur"
                        style="margin-left: 20px; background-color: #4FC1B0; border-color: #4FC1B0; color: #fff;">确定</el-button>
                </span>
            </div>
        </el-dialog>



        <!-- 退货模态框 -->
    <el-dialog title="" :visible.sync="isSalesModalVisible" width="50%">
      <h3>采购订单基础信息</h3>
      <div class="custom-div2">
        <el-button @click="TuiH">退货</el-button>
      </div>
      <el-form label-width="80px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="退货单号">
              <el-input
                v-model="addReturn.return_code"
                placeholder="自动获取系统编号"
                style="width: 200px"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="销售单号">
              <el-input
                v-model="addReturn.ord_number"
                style="width: 200px"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="退货日期">
              <el-date-picker
                style="width: 200px"
                v-model="addReturn.return_date"
                type="date"
                format="yyyy-MM-dd"
                placeholder="请选择日期"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="客户名称">
              <el-input
                v-model="addReturn.client_head"
                style="width: 200px"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系方式">
              <el-input
                v-model="addReturn.client_phone"
                placeholder="请输入"
                style="width: 200px"
                disabled
              />
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="审核人">
              <el-input
                v-model="addReturn.auditor"
                style="width: 200px"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="审核时间">
              <el-input
                v-model="addReturn.auditTime"
                style="width: 200px"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="审核状态">
              <el-input v-model="displayText" style="width: 200px" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="操作人员">
            <el-select v-model="addReturn.employee_name" placeholder="请选择操作人员" style="width: 200px">
              <el-option
                v-for="employee in OpersGou"
                :key="employee.employee_name"
                :label="employee.employee_name"
                :value="employee.employee_name"
               />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="退货原因">
              <el-input
                v-model="addReturn.returmReason"
                placeholder="请输入"
                type="textarea"
              />
            </el-form-item>
          </el-col>
          <el-form-item
            label="外键Id"
            style="position: relative; margin-left: -180px; top: 10px"
            v-if="Ycchange"
          >
            <el-input
              v-model="addReturn.sal_sales_ReturnReturn_Id"
              v-if="Ycchange"
            ></el-input>
          </el-form-item>
        </el-row>
      </el-form>


      <h3>退货产品明细</h3>
      <div style="overflow-x: auto">
        <el-table
          :data="fromEditUpdate"
          border
          stripe
          style="width: 100%"
          class="dataTable"
        >
          <el-table-column
            prop="fro_id"
            type="index"
            label="序号"
          ></el-table-column>
          <el-table-column
            prop="fro_purname"
            label="产品名称"
          ></el-table-column>

          <el-table-column
            prop="orders_unit"
            label="单位"
            width="60"
          ></el-table-column>
          <el-table-column
            prop="fro_puramount"
            label="采购数量"
            width="80"
          ></el-table-column>

          <el-table-column label="退货入库仓库" width="180">
            <template slot-scope="scope">
              <el-select
                v-model="scope.row.w_Name"
                auto-complete="off"
                placeholder="请选择退货仓库"
              >
                <el-option 
                          v-for="item in Wareh" 
                          :key="item.w_Name" 
                          :label="item.pr_wareh"
                          :value="item.w_Name">
                        </el-option>
              </el-select>
            </template>
          </el-table-column>

          <el-table-column label="退货数量">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.return_quantity"
                placeholder="请输入"
                @input="validateReturnQuantity(scope.row)"
              ></el-input>
            </template>
          </el-table-column>

          <el-table-column label="备注">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.return_remark"
                placeholder="请输入"
              ></el-input>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination-wrapper">
          <el-pagination
            @size-change="UdateSizeChange"
            @current-change="UpdateCurrentChange"
            :current-page="currentPage2"
            :page-sizes="[3, 6, 9, 12]"
            :page-size="pageSize2"
            layout="total, sizes, prev, pager, next, jumper"
            :total="UpdateItems"
          >
          </el-pagination>
        </div>
      </div>
    </el-dialog>
      </div>
    </div>
  </template>
  
<script>
import $http from '@/routers/base';
import { MessageBox } from 'element-ui';
import moment from 'moment'; 
  export default {
    data() {
      return {
        Puroptions:[],//查询产品名称--属性值
        order:[],//采购订单列表数据
        OrderWord:"",//搜索框
        SelectedDate:"",//时间搜索框
        DateString:'',//时间转型
        currentPage: 1, //当前页
        pageSize: 5, //每页显示数
        rows: 0, //总行数
        isAddModalVisible: false, // 控制新增弹窗的显示状态
        isAddProductVisible: false,//控制采购商品新增弹窗的显示状态
        //主表
        ListGou:[],//供货商联系人
        tableData:[],//采购商品列表
        ListAtt:[],//采购属性
        //采购订单主添加
        PurAdd:{
          ord_supplier:"",//联系人
          ord_supplier_company:"",//公司名称
          ord_phone:"",//手机号
          ord_supplier_address:"",//地址
          ord_number:"",//订单编号
          ord_attribute:"",//采购属性
          ord_types:"0",//商品种类
          ord_purchase_date:"",//采购日期
          ord_purchase_amount:"",//购货金额
          ord_discount_amount:"",//优惠金额
          ord_freight:"",//订单运费
          ord_amount_due:0,//应付金额
          ord_to_pay:"",//订单已付款
          IsDeleted:"",
          
          auditStatus: "",
          ord_state:"0",
          ord_warehouse:"0",

          auditor:"",
          auditTime:"",
          so_Return_status:'0',
        },
        //采购商品从添加
        FromAdd:{
          fro_id:"",//序号
          fro_purtotale:"",//采购产品属性
          fro_purname:"",//采购商品名称
          orders_unit:"",//单位
          fro_purprice:1,//采购单价
          fro_puramount:1,//采购数量
          fro_pursubtotal:1,//小计

          pur_Purchase_Orderord_id:"",
        },
        testArr:{

        },
        //从表
        currentPage1: 1, //当前页
        pageSize1: 3, //每页显示数
        totalItems: 0, //总行数
        FromDataAdd:[],//从添加
        index: 0,//当前数据项的下标
        list2:[],
        list3: [],
        units:[],//采购单位
        selectedRows: [], // 存储当前选中的行

        //主-查看
        EditPurUpdate:{
          ord_id:"",//ID
          ord_supplier:"",//联系人
          ord_supplier_company:"",//公司名称
          ord_phone:"",//手机号
          ord_supplier_address:"",//地址
          ord_number:"",//订单编号
          ord_attribute:"",//采购属性
          ord_types:"",//产品种类
          ord_purchase_date:"",//采购日期
          ord_purchase_amount:"",//购货金额
          ord_discount_amount:"",//优惠金额
          ord_freight:"",//订单运费
          ord_amount_due:0,//应付金额
          ord_to_pay:"",//订单已付款
          IsDeleted:"",
          auditStatus: "",
          auditor:"",
          auditTime:"",
          so_Return_status:"",
        },
        //从-查看修改
        EditFromUpdate:{
          fro_id:"",//序号
          fro_purtotale:"",//采购产品属性
          fro_purname:"",//采购商品名称
          orders_unit:"",//单位
          fro_purprice:1,//采购单价
          fro_puramount:1,//采购数量
          fro_pursubtotal:1,//小计

          pur_Purchase_Orderord_id:"",
        },
        //从-查看添加
        EditFromAdd:{
          fro_id:"",//序号
          fro_purtotale:"",//采购产品属性
          fro_purname:"",//采购商品名称
          orders_unit:"",//单位
          fro_purprice:1,//采购单价
          fro_puramount:1,//采购数量
          fro_pursubtotal:1,//小计

          pur_Purchase_Orderord_id:"",
        },
        currentPage2: 1, //当前页
        pageSize2: 5, //每页显示数
        UpdateItems: 0, //总行数
        fromEditUpdate:[],
        SelectPurChaseID:0,
        
        isUpdateModalVisible:false,   //主修改框
        isUpdateProductVisible:false,//从修改框
        subtotalSum: 0, // 用于存储小计总和
        isUpdateProduct:false,//从-修改
        



        isSalesModalVisible:false,
        selectedModelId2:0, 
        Ycchange: false,
        Wareh:[],
        OpersGou:[],//查询操作人员
        addReturn: {
          return_Id: "",
          return_code: "",
          ord_number: "",
          client_head: "",
          client_phone: "",
          Return_date: "",
          auditor: "",
          auditTime: "",
          AuditStatus: "",
          employee_name: "",
          returmReason: "",

          so_out_status: "", //销售订单/出库状态
      },
      };
    },

    computed: {
    // 计算属性，用于对从后端获取的物品属性列表进行去重
    uniqueList() {
      // 利用Set数据结构对数组进行去重
      const uniqueValues = [...new Set(this.list2.map(item => item.di_type))];
      // 根据去重后的值构造对象数组
      const uniqueList = uniqueValues.map(value => ({
        di_type: value,
      }));
      return uniqueList;
    },
    // 计算应付金额  
    computedAmountDue() {  
        let subtotal = 0;  
        this.FromDataAdd.forEach(item => {  
            subtotal += parseFloat(item.fro_pursubtotal); // 累加所有小计  
            
        });  
        //小计+运费-优惠=应付金额
        return parseFloat(subtotal) + parseFloat(this.PurAdd.ord_freight) - parseFloat(this.PurAdd.ord_discount_amount);  
    }, 
    computedAmountDue2() {
      // 计算小计、订单运费和优惠金额的总和
      return (
        parseFloat(this.subtotalSum) + // 小计总和
        parseFloat(this.EditPurUpdate.ord_freight) - // 订单运费
        parseFloat(this.EditPurUpdate.ord_discount_amount) // 优惠金额
      );
    },
    displayText() {
      return this.addReturn.auditStatus ? "已审核" : "未审核";
    },
  },
  
    methods: {
    //返回列表
    returnToList() {
      this.isAddModalVisible = false;
      this.PurAdd.ord_supplier = "";
      this.PurAdd.ord_supplier_company = "";
      this.PurAdd.ord_phone = "";
      this.PurAdd.ord_supplier_address = "";
      this.PurAdd.ord_number = "";
      this.PurAdd.ord_attribute = "";
      this.PurAdd.ord_purchase_date = "";
      this.PurAdd.ord_purchase_amount = "";
      this.PurAdd.ord_discount_amount = "";
      this.PurAdd.ord_freight = "";
      this.PurAdd.ord_amount_due = "";
      this.PurAdd.ord_to_pay = "";
      FromDataAdd=[];
      testArr=[];
    },

    //选中行
    handleSelectionChange(selection) {
      this.selectedRows = selection; // 更新选中的行
    },
    //复选框删除
    handleDeleteSelected(){
      if (this.selectedRows.length === 0) {
        this.$message.warning("请至少选择一个进行删除");
        return;
      }
      // 检查选中的订单中是否有已经审核通过的（audit_status === true）
      const auditedRows = this.selectedRows.filter(
        (row) => row.auditStatus === true
      );
      if (auditedRows.length > 0) {
        this.$message.warning(
          "选中的采购订单中已有部分订单已经审核通过，不能删除数据"
        );
        return;
      }
      this.$confirm("此操作将删除选中的销售订单, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
      .then(() => {
          this.selectedRows.forEach((row) => {
            this.deleteCustomers(row.ord_id);
          });
          this.PurFenYe();
          this.selectedRows = [];
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //逻辑删除方法
    deleteCustomers(ord_id){
      $http
        .delete(`PurchaseOrder/FromDelete/${ord_id}`)
        .then((response) => {
          this.$message({
            message: response,
            type: "success",
          });
          this.PurFenYe();
        })
        .catch((error) => {
          this.$message.error("删除失败，请稍后再试");
          console.error("Delete error:", error);
      });
    },
    //分页查询
    PurFenYe(){
        this.DateString = moment(this.SelectedDate).format('YYYY-MM-DD');
        this.where="1=1"
        if(this.OrderWord){
          this.where +=`and (ord_number like '%${this.OrderWord}%' or ord_supplier like '%${this.OrderWord}%' or ord_attribute like '%${this.OrderWord}%')`
        }
        if(this.OrderDate){
          this.where += ` AND ord_purchase_date = '${this.OrderDate}'`;
        }
         if(this.SelectedDate){
          this.where +=`and (CAST(ord_purchase_date AS DATE) ='${this.DateString}')`
        }
        $http.get('PurchaseOrder/OrderFenYe',{
            params:{
                currentPage: this.currentPage,
                pageSize: this.pageSize,
                where:this.where,
            }
        }).then(res=>{
            this.order=res.order;
            this.rows=res.rows;
        }).catch(error=>{
            console.error('Error fetching client data: ', error);
        })
    }, 
    Change: function(size) {
      this.pageSize = size;
      this.currentPage = 1;
      this.PurFenYe();
    },
    YmChange: function(page) {
      this.currentPage = page;
      this.PurFenYe();
    },
    //日期转型
    formatDate(dateString) {
            if (!dateString) {
                return '';
            }
            const date = new Date(dateString);
            if (isNaN(date.getTime())) {
                return '';
            }
            const year = date.getFullYear();
            const month = (date.getMonth() + 1).toString().padStart(2, '0');
            const day = date.getDate().toString().padStart(2, '0');
            return `${year}-${month}-${day}`;
    },


    // 显示主新增客户弹窗
    showAddModal() {
      this.isAddModalVisible = true;
      this.GouPur(); //供货商      
    },
    //查询供货商数据
    GouPur(){
      $http.get("PurchaseOrder/VenIndex")
          .then(res=>{
            this.ListGou=res;
          })
          .catch(err=>{
            alert(err);
          });
    },
    //选择供货商显示对应的数据
    onCustomerContactChange(Contact) {
          const contactInfo = this.ListGou.find(
              (c) => c.vendor_head === Contact
          );
          if (contactInfo) {
              this.PurAdd.ord_supplier_company = contactInfo.vendor_name;
              this.PurAdd.ord_phone = contactInfo.vendor_phone;
              this.PurAdd.ord_supplier_address = contactInfo.vendor_address;

              this.EditPurUpdate.ord_supplier_company = contactInfo.vendor_name;
              this.EditPurUpdate.ord_phone = contactInfo.vendor_phone;
              this.EditPurUpdate.ord_supplier_address = contactInfo.vendor_address;
          }
    },
    //添加
    async PurOrderAdd(){
      if (!this.PurAdd.ord_supplier) {
        this.$message.error('供货商不能为空！');
        return;
      }
      if (!this.PurAdd.ord_attribute) {
        this.$message.error('采购属性不能为空！');
        return;
      }
      if (!this.PurAdd.ord_purchase_date) {
        this.$message.error('采购日期不能为空！');
        return;
      }
      if (!this.PurAdd.ord_discount_amount) {
        this.$message.error('优惠金额不能为空！');
        return;
      }
      if (!this.PurAdd.ord_freight) {
        this.$message.error('订单运费不能为空！');
        return;
      }

      let modelclass = '0'; // 默认值为 '0'，以防止 totalItems 为 undefined 时出错
      if (this.totalItems !== undefined) {
        modelclass = this.totalItems.toString();
      }

      this.mainData={
        ord_supplier:this.PurAdd.ord_supplier,
        ord_supplier_company:this.PurAdd.ord_supplier_company,
        ord_phone:this.PurAdd.ord_phone,
        ord_supplier_address:this.PurAdd.ord_supplier_address,
        ord_number:this.PurAdd.ord_number,
        ord_attribute:this.PurAdd.ord_attribute,
        ord_types:modelclass,
        ord_purchase_date:this.PurAdd.ord_purchase_date,
        ord_purchase_amount:this.PurAdd.ord_purchase_amount,
        ord_discount_amount:this.PurAdd.ord_discount_amount,
        ord_freight:this.PurAdd.ord_freight,
        ord_amount_due:this.PurAdd.ord_amount_due,
        ord_to_pay:this.PurAdd.ord_to_pay,
        ord_state:"0",
        ord_warehouse:"0",
        isDeleted:false,
        auditStatus: false,
        auditor: null, //审核人
        auditTime: null, //审核时间
        so_Return_status:'0',
        pur_Purchase_From:this.FromDataAdd
      };
      $http.post('PurchaseOrder/OrderAdd', this.mainData)
        .then(res=>{
          if(res){
            this.$message.success('添加成功！');
            this.PurAdd.ord_supplier="";
            this.PurAdd.ord_supplier_company="";
            this.PurAdd.ord_phone="";
            this.PurAdd.ord_supplier_address="";
            this.PurAdd.ord_number="";
            this.PurAdd.ord_attribute="";
            this.PurAdd.ord_purchase_date="";
            this.PurAdd.ord_purchase_amount="";
            this.PurAdd.ord_discount_amount="";
            this.PurAdd.ord_freight="";
            this.PurAdd.ord_amount_due="";
            this.PurAdd.ord_to_pay="";
            this.PurFenYe();
            this.isAddModalVisible = false;
          } else {
              this.$message.error('添加失败！请重新添加！');
              
            }
        }).catch(error => {
            this.$message.error('添加失败：' + error.message);
      })
    },
    // 计算小计
    updateSubtotal() {
      this.FromAdd.fro_pursubtotal = (this.FromAdd.fro_purprice * this.FromAdd.fro_puramount).toFixed(4);

      this.EditFromUpdate.fro_pursubtotal = (this.EditFromUpdate.fro_purprice * this.EditFromUpdate.fro_puramount).toFixed(4);
    },
    //获取到应付金额，已付款，购货金额
    updateAmountDue() {
        // 当运费或优惠金额发生变化时，手动触发计算属性的更新
        this.$nextTick(() => {
            this.computedAmountDue;
            this.computedAmountDue2;
        });
        this.PurAdd.ord_amount_due=this.computedAmountDue;//应付金额
        this.PurAdd.ord_to_pay = this.computedAmountDue;///已付款
        this.PurAdd.ord_purchase_amount=this.computedAmountDue;//购货金额


        this.EditPurUpdate.ord_amount_due=this.computedAmountDue2;//应付金额
        this.EditPurUpdate.ord_to_pay = this.computedAmountDue2;///已付款
        this.EditPurUpdate.ord_purchase_amount=this.computedAmountDue2;//购货金额

    },
    

    PurHandleClose(done){
      this.FromDataAdd=[];
      this.testArr=[];
      this.totalItems=0;
      done();
    },
    //采购商品-从表添加
    async PurFromAdd(){
      this.isAddProductVisible = true;
      this.property();//查询物品属性
      this.fetchUnits(); //单位
    },
    //从表-虚拟数据添加
    SubmitModelForm() {
      if (!this.FromAdd.fro_purtotale) {
        this.$message.error('产品属性不能为空！');
        return;
      }
      if (!this.FromAdd.fro_purname) {
        this.$message.error('产品名称不能为空！');
        return;
      }
      if (!this.FromAdd.orders_unit) {
        this.$message.error('单位不能为空！');
        return;
      }
      if(this.testArr.length>0){
        this.FromDataAdd = this.testArr;
      }
      // 将表单数据添加到暂时保存数据的数组中
      this.FromDataAdd.push({
        fro_purtotale:this.FromAdd.fro_purtotale,
        fro_purname:this.FromAdd.fro_purname,
        orders_unit:this.FromAdd.orders_unit,
        fro_purprice:this.FromAdd.fro_purprice,
        fro_puramount:this.FromAdd.fro_puramount,
        fro_pursubtotal:this.FromAdd.fro_pursubtotal,
        index: this.FromDataAdd.length // 保存当前数据项的下标
      }),
      // 清空表单数据
      this.FromAdd.fro_purtotale='';
      this.FromAdd.fro_purname = '';
      this.FromAdd.orders_unit = '';
      this.FromAdd.fro_purprice = 1;
      this.FromAdd.fro_puramount = 1;
      this.FromAdd.fro_pursubtotal = 0;

    // 将 FromAdd 的值深拷贝给 testArr
      this.testArr = JSON.parse(JSON.stringify(this.FromDataAdd));
      // 更新总条目数
      this.totalItems = this.FromDataAdd.length;
      // 提示用户添加成功
      this.$message.success('添加成功！');
      this.isAddProductVisible = false; // 关闭对话框 

      this.currentPage1 = 1;
      this.End();
      // 输出数组的最后一个元素的索引
      console.log('数组最后一个元素的索引:', this.FromDataAdd.length);
      console.log(JSON.stringify(this.FromDataAdd));
      console.log(this.totalItems);
    },
    handleSizeChange: function(size) {
      this.pageSize1 = size;
      this.currentPage1 = 1;
      this.End();
    },
    handleCurrentChange: function(page) {
      this.currentPage1 = page;
      this.End();
    },
    //虚拟删除
    deleteCustomer(index) {
    // 首先确保下标在合法范围内
    if (index >= 0 && index < this.FromDataAdd.length) {
      // 从数组中删除指定下标的元素
      this.FromDataAdd.splice(index,1 );
      // 更新总条目数
      this.totalItems = this.FromDataAdd.length;
      // 深拷贝 allData 的值给 testArr
      this.testArr = JSON.parse(JSON.stringify(this.FromDataAdd));
      // 提示用户删除成功 
      this.$message.success('删除成功！');
    } else {
      // 如果下标不在合法范围内，给出相应的提示
      this.$message.error('无法删除，下标越界！');
    }
    },
    End() {
    // 根据当前页数和每页显示的条目数，截取相应的数据
     const startIndex = (this.currentPage1 - 1) * this.pageSize1;
     const endIndex = startIndex + this.pageSize1;
     this.FromDataAdd = this.testArr.slice(startIndex, endIndex);
    },
    //查询产品属性
    property(){
      $http
        .get("InventoryAlerts/Query")
          .then(res=>{
            this.list2 = res;
          })
          .catch(err => {
            alert(err);
          });
    },
    //查询产品名称--主添加
    nation(){
      this.FromAdd.fro_purname = "";
       if (this.FromAdd.fro_purtotale) {
         $http.get("InventoryAlerts/ResQuery?where=" + this.FromAdd.fro_purtotale)
          .then(res=>{
            this.list3 = res;
          })
          .catch(err => {
            alert(err);
          });
       }else {
        // 如果属性为空，清空物品名称列表
        this.list3 = [];
      }
    },
    //查询产品名称--从修改
    FromnationUpdate(){
      this.EditFromUpdate.fro_purname = "";
       if (this.EditFromUpdate.fro_purtotale) {
         $http.get("InventoryAlerts/ResQuery?where=" + this.EditFromUpdate.fro_purtotale)
          .then(res=>{
            this.list3 = res;
          })
          .catch(err => {
            alert(err);
          });
       }else {
        // 如果属性为空，清空物品名称列表
        this.list3 = [];
      }
    },
    //查询产品名称--从添加
    FromnationAdd(){
      this.EditFromAdd.fro_purname = "";
       if (this.EditFromAdd.fro_purtotale) {
         $http.get("InventoryAlerts/ResQuery?where=" + this.EditFromAdd.fro_purtotale)
          .then(res=>{
            this.list3 = res;
          })
          .catch(err => {
            alert(err);
          });
       }else {
        // 如果属性为空，清空物品名称列表
        this.list3 = [];
      }
    },
    //单位下拉
    fetchUnits() {
            $http.get('dict_data/Queryunit')
                .then((res) => {
                    // 根据type属性过滤出单位数据
                    this.units = res
                    this.units.forEach((unit) => {
                        console.log(unit.dd_label);
                    });
                })
                .catch((error) => {
                    console.error('Error fetching units from dictionary:', error);
                });
    },

    //采购订单-修改框
    editCustomers(row){
    
        this.isUpdateModalVisible = true;
        this.SelectPurChaseID=row.ord_id;
        this.EditFromUpdate.pur_Purchase_Orderord_id=this.SelectPurChaseID;
        this.GouPur(); //供货商
        this.fetchUpaheModeFrom();
        this.$set(this.EditPurUpdate,"ord_id",row.ord_id);
        this.$set(this.EditPurUpdate,"ord_supplier",row.ord_supplier);
        this.$set(this.EditPurUpdate,"ord_supplier_company",row.ord_supplier_company);
        this.$set(this.EditPurUpdate,"ord_phone",row.ord_phone);
        this.$set(this.EditPurUpdate,"ord_supplier_address",row.ord_supplier_address);
        this.$set(this.EditPurUpdate,"ord_number",row.ord_number);
        this.$set(this.EditPurUpdate,"ord_attribute",row.ord_attribute);
        this.$set(this.EditPurUpdate,"ord_purchase_date",row.ord_purchase_date);
        this.$set(this.EditPurUpdate,"ord_purchase_amount",row.ord_purchase_amount);
        this.$set(this.EditPurUpdate,"ord_discount_amount",row.ord_discount_amount);
        this.$set(this.EditPurUpdate,"ord_freight",row.ord_freight);
        this.$set(this.EditPurUpdate,"ord_amount_due",row.ord_amount_due);
        this.$set(this.EditPurUpdate,"ord_to_pay",row.ord_to_pay);
        this.$set(this.EditPurUpdate,"auditStatus",row.auditStatus);
        this.$set(this.EditPurUpdate,"so_Return_status",row.so_Return_status);
    },
    //查看-主修改
    PurOrderUpdate(){
      if (!this.EditPurUpdate.ord_supplier) {
        this.$message.error('供货商不能为空！');
        return;
      }
      if (!this.EditPurUpdate.ord_attribute) {
        this.$message.error('采购属性不能为空！');
        return;
      }
      if (!this.EditPurUpdate.ord_purchase_date) {
        this.$message.error('采购日期不能为空！');
        return;
      }
      if (!this.EditPurUpdate.ord_discount_amount) {
        this.$message.error('优惠金额不能为空！');
        return;
      }
      if (!this.EditPurUpdate.ord_freight) {
        this.$message.error('订单运费不能为空！');
        return;
      }
      // 检查审核状态，如果为 true，则不允许修改
      if (this.EditPurUpdate.auditStatus == true) {
        this.$message.error("修改失败：该订单已被审核，不能进行修改！");
        return;
      }
      if (this.EditPurUpdate.so_Return_status == "1" || this.EditPurUpdate.so_Return_status == "2") {
        this.$message.error("修改失败：该订单已提交退货申请，不能进行修改！");
        return;
      }
      let Cat = 0; 
      Cat=this.UpdateItems.toString();
      console.log("修改分页的总行数："+Cat);
      $http.put('PurchaseOrder/OrderUpdate',{
        ord_id:this.EditPurUpdate.ord_id,
        ord_supplier:this.EditPurUpdate.ord_supplier,
        ord_supplier_company:this.EditPurUpdate.ord_supplier_company,
        ord_phone:this.EditPurUpdate.ord_phone,
        ord_supplier_address:this.EditPurUpdate.ord_supplier_address,
        ord_number:this.EditPurUpdate.ord_number,
        ord_attribute:this.EditPurUpdate.ord_attribute,
        ord_types:Cat,
        ord_purchase_date:this.EditPurUpdate.ord_purchase_date,
        ord_purchase_amount:this.EditPurUpdate.ord_purchase_amount,
        ord_discount_amount:this.EditPurUpdate.ord_discount_amount,
        ord_freight:this.EditPurUpdate.ord_freight,
        ord_amount_due:this.EditPurUpdate.ord_amount_due,
        ord_to_pay:this.EditPurUpdate.ord_to_pay,
        ord_state:"0",
        ord_warehouse:"0",
        isDeleted: false,
        so_Return_status:'0',
        pur_Purchase_From:[{fro_purtotale:"",fro_purname:"",orders_unit:"",fro_purprice:1,fro_puramount:1,fro_pursubtotal:0}]
      })
      .then((res)=>{
        if(res){
          this.$message.success('修改成功！');
          this.PurFenYe();
          this.isUpdateModalVisible = false;
        }else{
          this.$message.error('修改失败！ 请重新修改！');
        }
      }).catch(error=>{
        this.$message.error('修改失败：'+error.message);
      })
    },
    //从表-查看分页
    fetchUpaheModeFrom(){
        this.where = "pur_Purchase_Orderord_id=" + this.SelectPurChaseID;
        $http.get('PurchaseOrder/FromChanFenYe',{
            params:{
                currentPage: this.currentPage2,
                pageSize: this.pageSize2,
                where:this.where,
            }
        }).then(res=>{
            this.fromEditUpdate=res.fromEditUpdate;
            this.UpdateItems=res.rows;

            // 计算小计总和
            let subtotalSum = 0;
            this.fromEditUpdate.forEach((item) => {
              subtotalSum += parseFloat(item.fro_pursubtotal);
            });
            this.subtotalSum = subtotalSum; // 将小计总和保存到组件变量中

            console.log("小计总和：", this.subtotalSum);
        }).catch(error=>{
            console.error('Error fetching client data: ', error);
        })
    },
    UdateSizeChange: function(size) {
      this.pageSize2 = size;
      this.currentPage2 = 1;
      this.fetchUpaheModeFrom();
    },
    UpdateCurrentChange: function(page) {
        this.currentPage2 = page;
        this.fetchUpaheModeFrom();
    },


    //查看-从表添加框
    PurFromUpdate(){
      if (this.EditPurUpdate.auditStatus === true) {
        this.$message.error("添加失败：该订单已被审核，不能进行添加！");
        return;
      }
      if (this.EditPurUpdate.so_Return_status == "1" || this.EditPurUpdate.so_Return_status == "2") {
        this.$message.error("修改失败：该订单已提交退货申请，不能进行修改！");
        return;
      }
      
      this.isUpdateProductVisible=true;
      this.property();//查询物品属性
      this.fetchUnits(); //单位
    },
    //从表添加确定
    FromUpdateSubmit(){
      if (!this.EditFromAdd.fro_purtotale) {
        this.$message.error('产品属性不能为空！');
        return;
      }
      if (!this.EditFromAdd.fro_purname) {
        this.$message.error('产品名称不能为空！');
        return;
      }
      if (!this.EditFromAdd.orders_unit) {
        this.$message.error('单位不能为空！');
        return;
      }
      $http.post('PurchaseOrder/FromAdd',{
        pur_Purchase_Orderord_id:this.SelectPurChaseID,
        fro_purtotale:this.EditFromAdd.fro_purtotale,
        fro_purname:this.EditFromAdd.fro_purname,
        orders_unit:this.EditFromAdd.orders_unit,
        fro_purprice:this.EditFromAdd.fro_purprice,
        fro_puramount:this.EditFromAdd.fro_puramount,
        fro_pursubtotal:this.EditFromAdd.fro_pursubtotal,
        isDeleted:false
      })
      .then(res=>{
        if(res){
          this.$message.success('添加成功！');
          this.EditFromAdd.fro_purtotale="";
          this.EditFromAdd.fro_purname="";
          this.EditFromAdd.orders_unit="";
          this.EditFromAdd.fro_purprice="";
          this.EditFromAdd.fro_puramount="";
          this.EditFromAdd.fro_pursubtotal="";
          this.fetchUpaheModeFrom();
          this.isUpdateProductVisible=false;
        }else{
          this.$message.error('添加失败！请重新添加！');
        }
      })
      .catch(error => {
         this.$message.error('添加失败：' + error.message);
     })
    },
    //查看-从表修改框
    UpdatePurEditFrom(row){
      if (this.EditPurUpdate.auditStatus === true) {
        this.$message.error("修改失败：该订单已被审核，不能进行修改！");
        return;
      }
      if (this.EditPurUpdate.so_Return_status == "1" || this.EditPurUpdate.so_Return_status == "2") {
        this.$message.error("修改失败：该订单已提交退货申请，不能进行修改！");
        return;
      }
      this.isUpdateProduct=true;
      this.property();//查询物品属性
      this.fetchUnits(); //单位
      this.$set(this.EditFromUpdate,"fro_id",row.fro_id);
      this.$set(this.EditFromUpdate,"fro_purtotale",row.fro_purtotale);
      this.$set(this.EditFromUpdate,"fro_purname",row.fro_purname);
      this.$set(this.EditFromUpdate,"orders_unit",row.orders_unit);
      this.$set(this.EditFromUpdate,"fro_purprice",row.fro_purprice);
      this.$set(this.EditFromUpdate,"fro_puramount",row.fro_puramount);
      this.$set(this.EditFromUpdate,"fro_pursubtotal",row.fro_pursubtotal);
    },
    //从表修改
    FromUpdatePur(){
      if (!this.EditFromUpdate.fro_purtotale) {
        this.$message.error('产品属性不能为空！');
        return;
      }
      if (!this.EditFromUpdate.fro_purname) {
        this.$message.error('产品名称不能为空！');
        return;
      }
      if (!this.EditFromUpdate.orders_unit) {
        this.$message.error('单位不能为空！');
        return;
      }
      $http.put('PurchaseOrder/FromUpdate',{
        fro_id:this.EditFromUpdate.fro_id,
        fro_purtotale:this.EditFromUpdate.fro_purtotale,
        fro_purname:this.EditFromUpdate.fro_purname,
        orders_unit:this.EditFromUpdate.orders_unit,
        fro_purprice:this.EditFromUpdate.fro_purprice,
        fro_puramount:this.EditFromUpdate.fro_puramount,
        fro_pursubtotal:this.EditFromUpdate.fro_pursubtotal,
        pur_Purchase_Orderord_id:this.EditFromUpdate.pur_Purchase_Orderord_id
      })
      .then(res=>{
        if(res){
          this.$message.success('修改成功！');
          this.fetchUpaheModeFrom();
          this.isUpdateProduct=false;
        }else{
          this.$message.error('修改失败！ 请重新修改！');
        }
      }).catch(error=>{
        this.$message.error('修改失败：'+error.message);
      })
    },
    //查看-从表删除
    UpdatedeleteCustomer(fro_id){
      if (this.EditPurUpdate.auditStatus === true) {
        this.$message.error("删除失败：该订单已被审核，不能进行删除！");
        return;
      }
      if (this.EditPurUpdate.so_Return_status == "1" || this.EditPurUpdate.so_Return_status == "2") {
        this.$message.error("删除失败：该订单已提交退货申请，不能进行修改！");
        return;
      }
      if (
        this.EditPurUpdate.so_Return_status == "1" ||
        this.EditPurUpdate.so_Return_status == "2"
      ) {
        this.$message.error("修改失败：该订单已提交退货申请，不能进行修改！");
        return;
      }
      MessageBox.confirm('确认删除删除该条记录吗？, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        $http.delete(`PurchaseOrder/FromPurDelete/${fro_id}`)
          .then(() => {
            this.$message({
              type: 'success',
              message: '删除成功！'
            })
            this.fetchUpaheModeFrom();
          }).catch(error=>{
            this.$message.error('删除失败：'+error.message)
          })
      })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '管理员取消了删除,删除无效哦！'
          })
        })
    },
    //审核
    handleAudit() {
      if (this.selectedRows.length === 0) {
        this.$message.warning("请至少选择一个采购订单进行审核");
        return;
      }

      // 检查选中的订单中是否有已经审核通过的（audit_status === true）
      const auditedRows = this.selectedRows.filter(
        (row) => row.auditStatus === true
      );
      if (auditedRows.length > 0) {
        this.$message.warning(
          "选中的采购订单中已有部分订单已经审核通过，不能再次审核"
        );
        return;
      }

      this.$confirm("此操作将审核选中的采购订单, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.selectedRows.forEach((row) => {
            this.auditSaleOrder(row.ord_id);
          });
          this.selectedRows = [];
          this.PurFenYe();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消审核",
          });
        });
    },
    //审核方法
    auditSaleOrder(ord_id) {
      $http
        .post(`PurchaseOrder/AuditSalesOrder/${ord_id}`)
        .then((response) => {
          this.$message({
            message: response,
            type: "success",
          });
          this.PurFenYe();
        })
        .catch((error) => {
          this.$message.error("审核失败，请稍后再试");
          console.error("Audit error:", error);
        });
    },
    //查询操作人员
    Opers(){
      $http.get("Employee/Query")
        .then(res=>{
          this.OpersGou=res;
        })
        .catch(err=>{
          alert(err);
        });
    },
    //入库仓库
    WarehAit(){
      $http.get('InventoryAlerts/IQuery')
        .then((res) => {
          // 根据type属性过滤出单位数据
          this.Wareh = res
          this.Wareh.forEach((unit) => {
          console.log(unit.dd_label);
          });
        })
        .catch((error) => {
            console.error('Error fetching units from dictionary:', error);
        });
    },
    //采购订单-退货框
    SalesCustomers(row){
      this.isSalesModalVisible = true;
      this.SelectPurChaseID=row.ord_id;
      this.EditPurUpdate.pur_Purchase_Orderord_id=this.SelectPurChaseID;
      this.PurFenYe();
      this.fetchUpaheModeFrom();
      this.$set(this.addReturn, "return_Id", row.return_Id);
      this.$set(this.addReturn, "ord_number", row.ord_number);
      this.$set(this.addReturn, "client_head", row.ord_supplier);
      this.$set(this.addReturn, "client_phone", row.ord_phone);
      this.$set(this.addReturn, "auditStatus", row.auditStatus);
      this.$set(this.addReturn, "auditor", row.auditor);
      this.$set(this.addReturn, "auditTime", row.auditTime);
      this.$set(this.addReturn, "return_status", row.so_Return_status);
      this.$set(this.addReturn, "so_out_status", row.ord_warehouse);
      console.log(JSON.stringify(row, null, 2));
    },
    TuiH() {
      if (!this.addReturn.return_date) {
        this.$message.error('请选择退货日期！');
        return;
      }
      if (!this.addReturn.employee_name) {
        this.$message.error('请选择操作人员！');
        return;
      }
      if (!this.addReturn.returmReason) {
        this.$message.error('请输入退货原因！');
        return;
      }
      this.mainData = {
        return_code: this.addReturn.return_code,
        ord_number: this.addReturn.ord_number,
        client_head: this.addReturn.client_head,
        client_phone: this.addReturn.client_phone,
        so_out_status: this.addReturn.so_out_status,
        return_status: "1",
        return_date: this.addReturn.return_date,
        isDeleted: false,
        auditor: this.addReturn.auditor,
        auditTime: this.addReturn.auditTime,
        auditStatus: false,
        employee_name: this.addReturn.employee_name,
        returmReason: this.addReturn.returmReason,
        pur_Sales_From: this.fromEditUpdate,
      };
      $http
        .post("PurSalesReturn/AddReturn", this.mainData)
        .then((response) => {
          if (response) {
            this.$message.success("退货成功！");
            this.$router.push("/pur_Zales_Return");
            this.PurFenYe();
            this.isSalesModalVisible = false;
          } else {
            this.$message.error("添加失败！请重新添加！");
          }
        })
        .catch((error) => {
          this.$message.error("添加失败：" + error.message);
        });
     },
    // 验证退货数量是否大于销售数量
    validateReturnQuantity(row) {
      if (row.return_quantity > row.fro_puramount) {
        this.$message.error("退货数量不能大于采购数量");
        // 如果退货数量大于销售数量，则重置为销售数量
        row.return_quantity = row.fro_puramount;
      }
    },
  },
    mounted(){
      this.PurFenYe();//采购主分页查询
      this.Opers();
      this.fetchUpaheModeFrom();
      this.WarehAit();
    },
  };
  </script>
  <style scoped src="../CSS/Purchase.css"></style>
  <style>
  /*表格单元格中的文本内容都将水平居中显示*/
  .centered-table .el-table__cell {
      text-align: center;
  }
  /*表格标题背景变色*/
  .centered-table .el-table__header th {
    background-color: #eeeeee;; /* 设置标题行的背景色 */
    color: #333; /* 设置标题行的文字颜色 */
  }
  
  .customer-list {
    background-color: #ffffff;
    padding: 20px;
  }
  
  /*按钮的样式*/
  .add-button {
    background-color: #4FC1B0;
    color: #ffffff;
  }
  
  .pagination {
    text-align: center;
    margin-top: 20px;
  }
  
  .add-button-bottom-right {
    position: absolute;
    bottom: 0;
    top: 140px; /* 将按钮相对于父容器顶部定位 */
    right: 100px;
    margin: 20px; /* 调整按钮与分割线的距离 */
  }
  .pagination-info {
    margin-bottom: 10px;
    text-align: right; /* 将当前显示条数等信息向右对齐 */
  }
  /* 调整对话框样式 */
  .el-dialog__body {  
    padding: 0px 10px 20px 10px; /* 调整内边距 */
  }
  /* 模态框 */
  #qw{
    position: fixed;
    top:5%;
    left: 5%;
    height: 600px; 
    overflow: hidden;
  }
  .ee{
      border-color: #4FC1B0;
  }

  .form-items-container {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    padding: 0 20px;
    /* 两边留出20px的空隙 */
}


/* 设置文本框的样式 */
.el-form-item__content {

    flex-grow: 1;
}

.form-item {
    flex: 0 0 calc(25% - 40px);
    /* 减去两侧各20px的空隙 */
    max-width: 250px;
    /* 设置文本框的最大宽度 */
    margin: 10px 0;
    /* 上下留出10px的空隙 */
}

.el-form-item__label {
    width: 120px;
    /* 可以调整标签的宽度 */
    text-align: right;
    padding-right: 10px;
}

@media (max-width: 800px) {
    .form-item {
        flex-basis: 100%;
        margin: 10px 0;
    }
}

.button-container {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    /* 垂直居中 */
    height: 100%;
    /* 确保按钮容器占据整个高度 */
    padding-top: 10px;
    float: left;
}

.custom-button {
    display: flex;
    align-items: center;
    /* 垂直居中 */
    justify-content: center;
    /* 水平居中 */
    background-color: #1ABC9C;
    width: 60px;
    height: 30px;
    color: #fff;
    font-size: 12px;
    border: none;
}

.custom-form {
    margin: 20px;
}

.kuang {
    width: 60px;
    font-size: small;
}

.orange-button {
    font-size: small;
}

.addmodel {
    left: 120px;
}

.caoz {
    width: 70px;
    font-size: small;
}

.custom-div2 button {
  background-color: #4fc1b0; /* 设置背景颜色为绿色 */
  border: none;
  color: white; /* 设置字体颜色为白色 */
  padding: 10px 20px;
  cursor: pointer;
  font-size: 15px; /* 设置字体大小为20px */
  position: relative;
  left: 83%;
  top: -30px;
  width: 100px;
  height: 40px;
}
  </style